package com.uuah.server.transformer;

import com.uuah.server.UuahServer;
import com.uuah.server.api.IUuahEventContext;
import com.uuah.server.api.IUuahMessage;
import com.uuah.server.config.i18n.ServerMessages;
import com.uuah.server.exception.transformer.TransformerException;
import com.uuah.server.message.UuahMessage;
import com.uuah.server.transport.RequestContextHelper;

/**
 * <code>AbstractMessageAwareTransformer</code> is a transformer that has a
 * reference to the current message. This message can be used obtains properties
 * associated with the current message useful to the transform. Note that when
 * part of a transform chain, the Message payload reflects the pre-transform
 * message state, unless there is no current event for this thread, then the
 * message will be a new DefaultUuahMessage with the src as its payload.
 * Transformers should always work on the src object not the message payload.
 *
 * <p>
 * update record:updator，update time，update content and version
 * </p>
 *
 * @author <a href="jonny_quan@hotmail.com">jonny</a>
 * @date 2009 2009-3-27 下午02:06:26
 * @version 1.0.0
 */
public abstract class AbstractMessageAwareTransformer extends
		AbstractTransformer {

	public boolean isSourceTypeSupported(Class aClass, boolean exactMatch) {
		return (super.isSourceTypeSupported(aClass, exactMatch) || IUuahMessage.class
				.isAssignableFrom(aClass));
	}

	public final Object doTransform(Object src, String encoding)
			throws TransformerException {
		IUuahMessage message;
		if (src instanceof IUuahMessage) {
			message = (IUuahMessage) src;
		} else if (UuahServer.getUuahContext().getConfiguration()
				.isAutoWrapMessageAwareTransform()) {
			message = new UuahMessage(src);
		} else {
			IUuahEventContext event = RequestContextHelper.getEventContext();
			if (event == null) {
				throw new TransformerException(ServerMessages
						.noCurrentEventForTransformer(), this);
			}
			message = event.getMessage();
			if (!message.getPayload().equals(src)) {
				throw new IllegalStateException(
						"Transform payload does not match current UuahEventContext payload");
			}
		}
		return transform(message, encoding);
	}

	public abstract Object transform(IUuahMessage message, String outputEncoding)
			throws TransformerException;

}